package com.example.questionnaire.controller;

import com.example.common.utils.PageUtils;
import com.example.common.utils.R;
import com.example.questionnaire.constant.QuestionnaireConstant;
import com.example.questionnaire.dto.AnswerUserDto;
import com.example.questionnaire.dto.ReleaseQuestionnaireDto;
import com.example.questionnaire.dto.SendListDto;
import com.example.questionnaire.entity.QuestionnaireEntity;
import com.example.questionnaire.service.QuestionnaireService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author hsz
 * @email 1416446590@qq.com
 * @date 2022-10-29 09:51:04
 */
@CrossOrigin
@RestController
@RequestMapping("questionnaire/questionnaire")
public class QuestionnaireController {
    @Autowired
    private QuestionnaireService questionnaireService;

    /**
     * 列表
     */
    @ApiOperation("查询（支持模糊查询，根据问卷标题questionnaireName," +
            "在Map类型的params上加入，非必须，map还有page、limit）")
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = questionnaireService.queryPage(params);
        return R.ok().put("data", page);
    }


    /**
     * 信息
     */
    @ApiOperation("查看问卷具体信息,题目之类的")
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id) {
        QuestionnaireEntity questionnaire = questionnaireService.getById(id);
        return R.ok().put("data", questionnaire);
    }

    /**
     * 保存
     */
//    @ApiOperation("创建问卷，时间数据由前端赋值到对象里")
    @PostMapping("/save")
    public R save(@RequestBody QuestionnaireEntity questionnaire) {
        questionnaireService.saveQuestionnaire(questionnaire);
        return R.ok();
    }


    /**
     * 修改
     */
    @ApiOperation("修改（后端写了判断是否处在发布状态）")
    @PostMapping("/update")
    public R update(@RequestBody QuestionnaireEntity questionnaire) {
        if(questionnaire.getStatus().equals(QuestionnaireConstant.stop.getStatus())){
            questionnaire.setEndTime(new Date());
            questionnaireService.updateById(questionnaire);
            return R.ok();
        }
        boolean flag = questionnaireService.updateByIdIsRelased(questionnaire);
        if (flag) {
            return R.ok();
        } else {
            return R.error("问卷已发布.暂时无法修改");
        }

    }

    /**
     * 删除
     */
    @ApiOperation("真删除，传入数组ids表示问卷数组")
    @PostMapping("/realDelete")
    public R realdelete(@RequestBody Integer[] ids) {
        questionnaireService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    @ApiOperation("已测试(后端写了判断否发布),伪删除(可批量删除)，json有个属性是数组ids表示问卷数组" +
            "，error是可能存在发布中的问卷，对发布中的问卷不做处理")
    @PostMapping("/delete")
    public R delete(@RequestBody AnswerUserDto answerUserDto) {
        boolean b = questionnaireService.removeTemporary(Arrays.asList(answerUserDto.getIds()));
        if(b){
            return R.ok();
        }else{
            return R.error("可删除问卷已删除，存在发布中的问卷无法删除");
        }

    }

    /**
     * 发布问卷
     */
    @ApiOperation("发布问卷,传入问卷的id,答者ids")
    @PostMapping("/release")
    public R release(@RequestBody ReleaseQuestionnaireDto releaseQuestionnaireDto) {
        questionnaireService.release(releaseQuestionnaireDto.getId(), releaseQuestionnaireDto.getAnswererIds());
        return R.ok();
    }
//TODO hsz：打算不用同一个接口，面向公众发布问卷，怎么收集，怎么创建答卷？？

    @ApiOperation("导入问卷")
    @PostMapping("/import/{id}")
    public R importQuestionnaire(@PathVariable("id") Integer id) {
        questionnaireService.importQuestionnaire(id);
        return R.ok();
    }

    @ApiOperation("恢复问卷")
    @PostMapping("/recover/{id}")
    public R recover(@PathVariable("id") Integer id) {
        questionnaireService.recover(id);
        return R.ok();
    }

    @ApiOperation("生成问卷链接")
    @PostMapping("/getShortUrlForLink/{id}")
    public R getShortUrlForLink(@PathVariable("id") Integer id) {
        String url = questionnaireService.getShortUrlForLink(id);
        return R.ok().put("data", url);
    }

    @ApiOperation("回收站的问卷,userId,page,limit")
    @GetMapping("/deletedList")
    public R deletedList(@RequestParam Map<String, Object> params){
        PageUtils page = questionnaireService.getDeletedList(params);
        return R.ok().put("data", page);
    }

    @GetMapping("/getListByKeyWord")
    public R findByKeyWord(@RequestParam("keyword")String keyword){
        List<QuestionnaireEntity> QList = questionnaireService.findByKeyWord(keyword);
        return R.ok().put("data",QList);
    }


    @ApiOperation("群发问卷")
    @PostMapping("/sendList")
    public R release1(@RequestBody SendListDto sendListDto) {
        Integer quesId=sendListDto.getQuesId();
        Integer[] teamIds = sendListDto.getTeamIds();
        List<Integer> result = questionnaireService.findByTeamIds(teamIds);
        Integer[] answerers = new Integer[result.size()];
        for(int i=0;i<result.size();i++){
            answerers[i] = result.get(i);
            System.out.println(answerers[i]);
        }
        System.out.println(answerers);
        questionnaireService.release(quesId,answerers);
        return R.ok();
    }
}
